package sputils

import (
	"fmt"
	"gitee.com/ymofen/gobase/gojson"
	"gitee.com/ymofen/golang/strmap"
	"sort"
)

type StrMapV2Wapper struct {
	svmap strmap.StrMap
}

func NewStrMapV2Wapper(sv strmap.StrMap) *StrMapV2Wapper {
	return &StrMapV2Wapper{sv}
}

func NewSVMapV2() *StrMapV2Wapper {
	return &StrMapV2Wapper{svmap: strmap.NewStrMap()}
}

func (s StrMapV2Wapper) StringByName(name string, def string) string {
	return s.svmap.StringByName(name, def)
}

func (s StrMapV2Wapper) String() string {
	return s.AsJSONStringEx(false, false)
}

func (s StrMapV2Wapper) IsString() bool {
	return false
}

func (s StrMapV2Wapper) IsObject() bool {
	return true
}

func (s StrMapV2Wapper) Write2StrMap(strMap strmap.StrMap) int {
	strMap.CopyFrom(s.svmap)
	return len(s.svmap)
}

func (s StrMapV2Wapper) AsJSONStringEx(escape bool, format bool) string {
	var jb gojson.JSONBuilder
	jb.ObjectBegin()
	s.svmap.SortRange(func(k, v string) bool {
		jb.Add(k, v)
		return true
	})
	jb.ObjectEnd()
	return jb.String()
}

func (s StrMapV2Wapper) SetKeyValue(key string, val interface{}) {
	s.svmap[key] = fmt.Sprintf("%v", val)
}

func (s StrMapV2Wapper) SetKeyValues(kvPairs ...interface{}) {
	if len(kvPairs)%2 != 0 {
		panic(fmt.Sprintf("invalid key-value pairs, %d", len(kvPairs)))
	}
	for i := 0; i < len(kvPairs); i += 2 {
		s.svmap[fmt.Sprintf("%v", kvPairs[i])] = fmt.Sprintf("%v", kvPairs[i+1])
	}
}

func (s StrMapV2Wapper) GetKeys() []string {
	keys := make([]string, 0, len(s.svmap))
	for k := range s.svmap {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}
